package cn.migu.music.hangupsms.utils;

import cn.migu.music.common.exception.SystemException;
import cn.migu.music.common.utils.LogUtils;
import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.CompressionMethod;
import net.lingala.zip4j.model.enums.EncryptionMethod;

import java.io.File;
import java.util.Set;

@Slf4j
public class CompressUtils {
    private CompressUtils() {}

    /**
     * 压缩文件
     * 
     * @param filePathSet
     * @param password
     * @param outputFilePath
     */
    public static void compressAndEncryptFiles(Set<File> filePathSet,
                                               String password,
                                               String outputFilePath) {
        // 开始压缩
        try (ZipFile zipFile = new ZipFile(outputFilePath, password.toCharArray())) {
            ZipParameters parameters = new ZipParameters();
            parameters.setCompressionMethod(CompressionMethod.DEFLATE);
            parameters.setCompressionLevel(CompressionLevel.NORMAL);
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD);
            for (File file : filePathSet) {
                if (file.exists()) {
                    zipFile.addFile(file, parameters);
                    LogUtils.info(log, "Files compressed and encrypted successfully:%s ", file.getPath());
                } else {
                    LogUtils.error(log, "File not found:%s", file.getPath());
                }
            }
        } catch (Exception ex) {
            LogUtils.error(ex, log, "压缩异常");
            throw SystemException.newInstance("compress files error", ex);
        }

        LogUtils.info(log, "压缩成功,压缩后文件名:%s", outputFilePath);

        for (File file : filePathSet) {
            // 删除txt文件
            LocalFileUtil.deleteLocalFile(file.getPath());
        }
    }
}
